package com.demo.admin.service.impl;

import java.util.*;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson2.JSON;
import com.demo.admin.domain.bo.AccessToken;
import com.demo.admin.domain.param.OauthTokenParam;
import com.demo.admin.domain.result.OauthTokenResult;
import com.demo.admin.service.OauthService;
import com.demo.common.exception.ErrorEnums;
import com.demo.common.exception.DemoException;
import com.demo.common.util.DemoUtil;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * OauthServiceImpl
 * 
 * @author demo
 * @data 2022-02-26 22:46:35
 */
@Slf4j
@Service
public class OauthServiceImpl implements OauthService {

    /**
     * 获取token
     * 
     * @author demo
     */
    @Override
    public OauthTokenResult token(OauthTokenParam param) {
        String username = param.getUsername();
        String password = param.getPassword();
        if (!"admin".equals(username) || !"111111".equals(password)) {
            log.error("cannot find gateway account, username [{}]", username);
            throw new DemoException(ErrorEnums.GET_ACCESS_TOKEN_FAILED);
        }
        Date now = new Date();
        Integer expiresIn = 60*60*24*7;
        Date expiredTime = DateUtil.offsetSecond(now, expiresIn);
        AccessToken accessToken = new AccessToken();
        accessToken.setGatewayAccountId(1);
        accessToken.setUsername(username);
        accessToken.setUsertype("admin");
        accessToken.setExpiredTime(expiredTime);
        OauthTokenResult oauthTokenResult = new OauthTokenResult();
        oauthTokenResult.setAccessToken(DemoUtil.desEncrypt(JSON.toJSONString(accessToken)));
        oauthTokenResult.setExpiredTime(expiredTime);
        return oauthTokenResult;
    }

}
